package com.garlicts.excel.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;

public class MapUtil {

	/**
	 * Map转成实体 
	 */
	public static <T> T map2Javabean(Map<String, Object> map,  Class<T> clazz) throws Exception {
		
		if(map == null || map.isEmpty()) {
			return null;
		}
		
		ConvertUtils.register(new LongConverter(null), Long.class);
		
		ConvertUtils.register(new ShortConverter(null), Short.class);
		
		ConvertUtils.register(new IntegerConverter(null), Integer.class);
		
		ConvertUtils.register(new DoubleConverter(null), Double.class);
		
		DateConverter dateConverter = new DateConverter(null);
		dateConverter.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss", 
				"yyyy/MM/dd", "yyyy/MM/dd HH", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH:mm:ss",
				"yyyy年MM月dd日", "yyyy年MM月dd日 HH时", "yyyy年MM月dd日 HH时:mm分", "yyyy年MM月dd日 HH时mm分ss秒"});
		ConvertUtils.register(dateConverter, Date.class);
		
		ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
		
		T instance = clazz.newInstance();
		BeanUtils.populate(instance, map);
		return instance;
		
	}
	
	/**
	 *	实体转成Map 
	 */
	public static Map<String, Object> javabean2Map(Object obj){
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(obj == null) {
			return map;
		}
		
		Field[] declaredFields = obj.getClass().getDeclaredFields();
		for(Field field : declaredFields) {
			field.setAccessible(true);
			try {
				map.put(field.getName(), field.get(obj));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return map;
		
	}
	
}
